<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token }}">
    <title>二次元博客</title>
{#    <script src="https://fastly.jsdelivr.net/gh/stevenjoezhang/live2d-widget@latest/autoload.js"></script>#}
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#7B68EE',
                        secondary: '#FF69B4',
                        dark: '#1A1A2E',
                        light: '#F5F5F7',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                        code: ['Consolas', 'Monaco', 'monospace'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            /* 流星动画样式优化 */
            .meteor {
                width: 1px;
                height: 100px;
                background: linear-gradient(to bottom, rgba(255,255,255,0), rgba(255,255,255,0.8));
                border-radius: 50%;
                transform-origin: top center;
                opacity: 0;
            }

            .meteor-1 { top: 10%; left: 20%; transform: rotate(-15deg); }
            .meteor-2 { top: 20%; left: 60%; transform: rotate(10deg); height: 80px; }
            .meteor-3 { top: 5%; left: 40%; transform: rotate(-5deg); height: 120px; }
            .meteor-4 { top: 30%; left: 80%; transform: rotate(-20deg); height: 90px; }
            .meteor-5 { top: 15%; left: 10%; transform: rotate(5deg); height: 70px; }

            @keyframes meteor {
                0% {
                    transform: rotate(var(--rotation)) translateY(-100%);
                    opacity: 0;
                }
                10% {
                    opacity: 1;
                }
                90% {
                    opacity: 1;
                }
                100% {
                    transform: rotate(var(--rotation)) translateY(100vh);
                    opacity: 0;
                }
            }

            .animate-meteor {
                animation: meteor 3s linear infinite;
            }

            /* 移动端看板娘层级优化 */
            @media (max-width: 768px) {
                #live2d-widget {
                    z-index: 9999 !important;
                    position: fixed !important;
                }
            }

            /* Toast样式补充 */
            .translate-y-16 {
                transform: translateY(4rem);
            }
            .opacity-0 {
                opacity: 0;
            }

            /* 分类标签样式 */
            .category-tag {
                position: absolute;
                top: 3px;
                right: 3px;
                z-index: 10;
                padding: 2px 8px;
                border-radius: 12px;
                font-size: 12px;
                font-weight: 500;
                background-color: rgba(123, 104, 238, 0.8);
                color: white;
                backdrop-filter: blur(2px);
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
                transition: all 0.3s ease;
            }

            .category-tag:hover {
                transform: scale(1.05);
                background-color: rgba(123, 104, 238, 1);
            }

            .category-tag.uncategorized {
                background-color: rgba(100, 116, 139, 0.8);
            }

            .category-tag.uncategorized:hover {
                background-color: rgba(100, 116, 139, 1);
            }

            /* 富文本编辑器样式 */
            .rich-text-toolbar {
                border-bottom: 1px solid #374151;
                padding: 0.5rem 1rem;
                display: flex;
                flex-wrap: wrap;
                gap: 0.5rem;
                background-color: rgba(30, 41, 59, 0.5);
            }

            .rich-text-btn {
                padding: 0.25rem 0.75rem;
                border-radius: 4px;
                border: 1px solid transparent;
                background-color: rgba(123, 104, 238, 0.2);
                color: #e2e8f0;
                cursor: pointer;
                transition: all 0.2s ease;
                display: flex;
                align-items: center;
                gap: 0.25rem;
            }

            .rich-text-btn:hover {
                background-color: rgba(123, 104, 238, 0.4);
            }

            .rich-text-btn.active {
                background-color: rgba(123, 104, 238, 0.6);
                border-color: rgba(123, 104, 238, 0.8);
            }

            .rich-text-select {
                padding: 0.25rem 0.75rem;
                border-radius: 4px;
                border: 1px solid #4b5563;
                background-color: rgba(30, 41, 59, 0.8);
                color: #e2e8f0;
                cursor: pointer;
            }

            .rich-text-editor {
               height: 400px;
               min-height: 700px;
                padding: 1rem;
               outline: none;
               overflow-y: scroll;
            }

            .rich-text-editor p {
                margin-bottom: 1rem;
            }

            .rich-text-editor blockquote {
                border-left: 4px solid #7B68EE;
                padding-left: 1rem;
                margin: 1rem 0;
                color: #94a3b8;
            }

            .rich-text-editor pre {
                background-color: rgba(15, 23, 42, 0.8);
                padding: 1rem;
                border-radius: 6px;
                overflow-x: auto;
                margin: 1rem 0;
                font-family: 'Consolas', 'Monaco', monospace;
            }

            .rich-text-editor code {
                background-color: rgba(15, 23, 42, 0.6);
                padding: 0.2rem 0.4rem;
                border-radius: 4px;
                font-family: 'Consolas', 'Monaco', monospace;
            }
        }
    </style>
</head>
<body class="bg-dark text-light min-h-screen flex flex-col">
    <!-- 流星背景 -->
    <div class="fixed inset-0 z-0 overflow-hidden">
        <div class="meteor meteor-1 absolute animate-meteor" style="--rotation: -15deg; animation-delay: 0s;"></div>
        <div class="meteor meteor-2 absolute animate-meteor" style="--rotation: 10deg; animation-delay: 2s;"></div>
        <div class="meteor meteor-3 absolute animate-meteor" style="--rotation: -5deg; animation-delay: 4s;"></div>
        <div class="meteor meteor-4 absolute animate-meteor" style="--rotation: -20deg; animation-delay: 6s;"></div>
        <div class="meteor meteor-5 absolute animate-meteor" style="--rotation: 5deg; animation-delay: 8s;"></div>
    </div>

    <!-- 导航栏 -->
    <nav class="relative z-10 bg-dark/80 backdrop-blur-md py-4 px-6 md:px-12">
        <div class="container mx-auto flex justify-between items-center">
            <a href="#" class="text-2xl font-bold text-primary flex items-center">
                <i class="fa fa-pencil-square-o mr-2"></i>
                <span>二次元博客</span>
            </a>

            <div class="hidden md:flex items-center space-x-8">
                <a href="{% url 'index' %}" class="text-primary border-b-2 border-primary pb-1">首页</a>
                <a href="#" class="text-light hover:text-primary transition-colors duration-300">专题合集</a>
                <a href="{% url 'hot' %}" class="text-light hover:text-primary transition-colors duration-300">热门</a>
                <a href="{% url 'about' %}" class="text-light hover:text-primary transition-colors duration-300">关于</a>
            </div>

            <div class="flex items-center space-x-4">
                <button id="create-post-btn" class="hidden md:flex items-center px-4 py-2 bg-primary hover:bg-primary/90 text-white rounded-full transition-all duration-300 transform hover:scale-105">
                    <i class="fa fa-pencil mr-2"></i>
                    <span>写博客</span>
                </button>

                <div id="user-menu" class="hidden items-center space-x-3">
                    <img id="user-avatar" src="https://picsum.photos/id/64/200/200" alt="用户头像" class="w-8 h-8 rounded-full object-cover border-2 border-primary">
                    <span id="username" class="text-light"></span>
                    <button id="logout-btn" class="text-light hover:text-primary transition-colors duration-300">
                        <i class="fa fa-sign-out"></i>
                    </button>
                </div>

                <div id="guest-menu" class="flex items-center space-x-3">
                    <button id="login-btn" class="px-4 py-2 border border-primary text-primary hover:bg-primary/10 rounded-full transition-all duration-300">
                        登录
                    </button>
                    <button id="register-btn" class="px-4 py-2 bg-primary text-white hover:bg-primary/90 rounded-full transition-all duration-300 transform hover:scale-105">
                        注册
                    </button>
                </div>

                <button id="mobile-menu-btn" class="md:hidden text-light hover:text-primary transition-colors duration-300">
                    <i class="fa fa-bars text-xl"></i>
                </button>
            </div>
        </div>


        <!-- 移动端菜单 -->
        <div id="mobile-menu"class="md:hidden hidden bg-dark/95 backdrop-blur-md absolute w-full">
           <div class="flex flex-col p-4 space-y-4">
                <a href="{% url 'index' %}" class="text-primary py-2">首页</a>
                <a href="#" class="text-light hover:text-primary transition-colors duration-300 py-2">专题合集</a>
                <a href="{% url 'hot' %}" class="text-light hover:text-primary transition-colors duration-300 py-2">热门</a>
                <a href="{% url 'about' %}" class="text-light hover:text-primary transition-colors duration-300 py-2">关于</a>
                <button id="mobile-create-post-btn" class="flex items-center px-4 py-2 bg-primary hover:bg-primary/90 text-white rounded-full transition-all duration-300 transform hover:scale-105">
                    <i class="fa fa-pencil mr-2"></i>
                    <span>写博客</span>
                </button>
            </div>
        </div>
    </nav>
   <main class="relative z-10 flex-grow container mx-auto px-2 md:px-12 py-8">
    <!-- 主内容区容器 -->
    <div class="flex flex-col lg:flex-row gap-8 min-h-[calc(100vh-4rem)]">
        <!-- 左侧边栏：实时热点新闻 -->
        <div class="lg:w-1/4 sticky top-8 self-start">
            <div class="relative z-5 mb-4 group">
                <h2 class="text-xl font-bold text-primary mb-4 flex items-center group-hover:translate-x-1 transition-transform">
                    <i class="fa fa-bolt mr-2"></i>实时新闻
                </h2>
                <ul class="space-y-4">
                    {% for news in news_list.data.items|slice:":5" %}
                    <li class="pb-4 border-b border-gray-50 last:border-0 last:pb-0 transform hover:-translate-y-1 transition-all duration-300">
                        <a href="{{ news.url }}" target="_blank" class="group">
                            <!-- 新闻标题 -->
                            <div class="text-purple-300 group-hover:text-purple-100 transition-colors line-clamp-2 mb-1">
                                {{ news.title }}
                            </div>
                            <!-- 新闻热度和时间 -->
                            <div class="text-xs text-gray-500 flex items-center">
                                <span class="inline-block w-1.5 h-1.5 rounded-full bg-red-400 mr-1 animate-pulse"></span>
                                {{ news.views }} 次浏览 ·
                                <span class="ml-1">{{ news.published_at|timesince }}前</span>
                            </div>
                        </a>
                    </li>
                    {% empty %}
                    <li class="text-gray-500 text-center py-6">
                        <div class="flex flex-col items-center">
                            <i class="fa fa-newspaper-o text-2xl mb-2 opacity-30"></i>
                            暂无热点新闻数据
                        </div>
                    </li>
                    {% endfor %}
                </ul>
            </div>
        </div>

        <!-- 中间内容：博客列表 -->
        <div class="lg:w-2/4">
            <div class="mb-8 transform hover:scale-[1.01] transition-transform">
                <h1 class="text-3xl md:text-4xl font-bold text-white mb-2 bg-clip-text text-transparent bg-gradient-to-r from-primary to-purple-400">最新博客</h1>
                <p class="text-gray-400">发现创作者们的精彩分享</p>
            </div>

            <div id="articles-container" class="space-y-8">
                <!-- 博客文章将通过JavaScript动态加载 -->
                <div id="loading-placeholder" class="hidden py-12 text-center">
                    <div class="inline-block animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary"></div>
                    <p class="mt-3 text-gray-400">加载中...</p>
                </div>
            </div>

            <div class="text-center mt-12">
                <button id="load-more-btn" class="px-6 py-3 bg-primary/20 hover:bg-primary/30 text-primary rounded-full transition-all duration-300 flex items-center mx-auto group">
                    加载更多 <i class="fa fa-refresh ml-2 group-hover:rotate-180 transition-transform duration-500"></i>
                </button>
                <p id="end-message" class="mt-4 text-gray-500 hidden">已加载全部内容</p>
            </div>
        </div>

        <!-- 右侧边栏：用户信息和热门标签 -->
        <div class="lg:w-1/4">
            <!-- 热门标签卡片 -->
            <div class="bg-dark/60 backdrop-blur-md rounded-2xl p-6 shadow-xl border border-primary/20 mb-8 transform hover:shadow-primary/10 transition-all duration-300">
                <h2 class="text-xl font-bold text-primary mb-4 flex items-center">
                    <i class="fa fa-tags mr-2"></i>热门标签
                </h2>
                <div class="flex flex-wrap gap-2">
                    <a href="#" class="px-3 py-1 bg-primary/20 hover:bg-primary/30 text-primary rounded-full text-sm transition-all duration-300 hover:scale-105">#二次元</a>
                    <a href="#" class="px-3 py-1 bg-primary/20 hover:bg-primary/30 text-primary rounded-full text-sm transition-all duration-300 hover:scale-105">#技术</a>
                    <a href="#" class="px-3 py-1 bg-primary/20 hover:bg-primary/30 text-primary rounded-full text-sm transition-all duration-300 hover:scale-105">#生活</a>
                    <a href="#" class="px-3 py-1 bg-primary/20 hover:bg-primary/30 text-primary rounded-full text-sm transition-all duration-300 hover:scale-105">#游戏</a>
                    <a href="#" class="px-3 py-1 bg-primary/20 hover:bg-primary/30 text-primary rounded-full text-sm transition-all duration-300 hover:scale-105">#动漫</a>
                    <a href="#" class="px-3 py-1 bg-primary/20 hover:bg-primary/30 text-primary rounded-full text-sm transition-all duration-300 hover:scale-105">#音乐</a>
                    <a href="#" class="px-3 py-1 bg-primary/20 hover:bg-primary/30 text-primary rounded-full text-sm transition-all duration-300 hover:scale-105">#旅行</a>
                    <a href="#" class="px-3 py-1 bg-primary/20 hover:bg-primary/30 text-primary rounded-full text-sm transition-all duration-300 hover:scale-105">#美食</a>
                </div>
            </div>

            <!-- 活跃用户卡片 -->
            <div class="bg-dark/60 backdrop-blur-md rounded-2xl p-6 shadow-xl border border-primary/20 transform hover:shadow-primary/10 transition-all duration-300">
                <h2 class="text-xl font-bold text-primary mb-4 flex items-center">
                    <i class="fa fa-users mr-2"></i>活跃用户
                </h2>
                <div class="space-y-4">
                    <div class="flex items-center space-x-3 p-2 rounded-lg hover:bg-primary/10 transition-colors">
                        <img src="https://picsum.photos/id/1005/100/100" alt="用户头像" class="w-10 h-10 rounded-full object-cover ring-2 ring-primary/30">
                        <div>
                            <h3 class="font-medium text-white">用户1</h3>
                            <p class="text-xs text-gray-400">发布了12篇博客</p>
                        </div>
                        <button class="ml-auto text-xs px-2 py-1 bg-primary/20 hover:bg-primary/30 rounded-full transition-colors">
                            关注
                        </button>
                    </div>
                    <div class="flex items-center space-x-3 p-2 rounded-lg hover:bg-primary/10 transition-colors">
                        <img src="https://picsum.photos/id/1012/100/100" alt="用户头像" class="w-10 h-10 rounded-full object-cover ring-2 ring-primary/30">
                        <div>
                            <h3 class="font-medium text-white">用户2</h3>
                            <p class="text-xs text-gray-400">发布了8篇博客</p>
                        </div>
                        <button class="ml-auto text-xs px-2 py-1 bg-primary/20 hover:bg-primary/30 rounded-full transition-colors">
                            关注
                        </button>
                    </div>
                    <div class="flex items-center space-x-3 p-2 rounded-lg hover:bg-primary/10 transition-colors">
                        <img src="https://picsum.photos/id/1027/100/100" alt="用户头像" class="w-10 h-10 rounded-full object-cover ring-2 ring-primary/30">
                        <div>
                            <h3 class="font-medium text-white">用户3</h3>
                            <p class="text-xs text-gray-400">发布了5篇博客</p>
                        </div>
                        <button class="ml-auto text-xs px-2 py-1 bg-primary/20 hover:bg-primary/30 rounded-full transition-colors">
                            关注
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

    <!-- 模态框：登录 -->
    <div id="login-modal" class="fixed inset-0 z-50 flex items-center justify-center hidden">
        <div class="absolute inset-0 bg-black/70 backdrop-blur-sm" id="login-overlay"></div>
        <div class="relative bg-dark border border-primary/30 rounded-2xl shadow-2xl p-8 w-full max-w-md transform transition-all duration-300 scale-95 opacity-0" id="login-modal-content">
            <button id="close-login-modal" class="absolute top-4 right-4 text-gray-400 hover:text-white transition-colors duration-300">
                <i class="fa fa-times text-xl"></i>
            </button>
            <h2 class="text-2xl font-bold text-primary mb-6 text-center">登录</h2>
            <form id="login-form" class="space-y-4">
                <div>
                    <label for="login-username" class="block text-sm font-medium text-gray-400 mb-1">用户名</label>
                    <input type="text" id="login-username" class="w-full px-4 py-2 bg-dark/50 border border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300" placeholder="请输入用户名">
                </div>
                <div>
                    <label for="login-password" class="block text-sm font-medium text-gray-400 mb-1">密码</label>
                    <input type="password" id="login-password" class="w-full px-4 py-2 bg-dark/50 border border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300" placeholder="请输入密码">
                </div>
                <button type="submit" class="w-full px-4 py-3 bg-primary hover:bg-primary/90 text-white rounded-lg transition-all duration-300 transform hover:scale-[1.02]">登录</button>
            </form>
            <p class="text-center mt-4 text-gray-400">
                还没有账号？ <button id="switch-to-register" class="text-primary hover:underline">立即注册</button>
            </p>
        </div>
    </div>

    <!-- 模态框：注册 -->
    <div id="register-modal" class="fixed inset-0 z-50 flex items-center justify-center hidden">
        <div class="absolute inset-0 bg-black/70 backdrop-blur-sm" id="register-overlay"></div>
        <div class="relative bg-dark border border-primary/30 rounded-2xl shadow-2xl p-8 w-full max-w-md transform transition-all duration-300 scale-95 opacity-0" id="register-modal-content">
            <button id="close-register-modal" class="absolute top-4 right-4 text-gray-400 hover:text-white transition-colors duration-300">
                <i class="fa fa-times text-xl"></i>
            </button>
            <h2 class="text-2xl font-bold text-primary mb-6 text-center">注册</h2>
            <form id="register-form" class="space-y-4">
                <div>
                    <label for="register-username" class="block text-sm font-medium text-gray-400 mb-1">用户名</label>
                    <input type="text" id="register-username" class="w-full px-4 py-2 bg-dark/50 border border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300" placeholder="请输入用户名">
                </div>
                <div>
                    <label for="register-email" class="block text-sm font-medium text-gray-400 mb-1">邮箱</label>
                    <input type="email" id="register-email" class="w-full px-4 py-2 bg-dark/50 border border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300" placeholder="请输入邮箱">
                </div>
                <div>
                    <label for="register-password" class="block text-sm font-medium text-gray-400 mb-1">密码</label>
                    <input type="password" id="register-password" class="w-full px-4 py-2 bg-dark/50 border border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300" placeholder="请输入密码">
                </div>
                <div>
                    <label for="register-confirm-password" class="block text-sm font-medium text-gray-400 mb-1">确认密码</label>
                    <input type="password" id="register-confirm-password" class="w-full px-4 py-2 bg-dark/50 border border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300" placeholder="请再次输入密码">
                </div>
                <button type="submit" class="w-full px-4 py-3 bg-primary hover:bg-primary/90 text-white rounded-lg transition-all duration-300 transform hover:scale-[1.02]">注册</button>
            </form>
            <p class="text-center mt-4 text-gray-400">
                已有账号？ <button id="switch-to-login" class="text-primary hover:underline">立即登录</button>
            </p>
        </div>
    </div>

    <!-- 模态框：写博客 -->
    <div id="create-post-modal" class="fixed inset-0 z-50 flex items-center justify-center hidden">
        <div class="absolute inset-0 bg-black/70 backdrop-blur-sm" id="create-post-overlay"></div>
        <div class="relative bg-dark border border-primary/30 rounded-2xl shadow-2xl p-8 w-full max-w-3xl max-h-[90vh] overflow-y-auto transform transition-all duration-300 scale-95 opacity-0" id="create-post-modal-content">
            <button id="close-create-post-modal" class="absolute top-4 right-4 text-gray-400 hover:text-white transition-colors duration-300">
                <i class="fa fa-times text-xl"></i>
            </button>
            <h2 class="text-2xl font-bold text-primary mb-6">写博客</h2>
            <form id="create-post-form" class="space-y-6">
                <div>
                    <label for="post-title" class="block text-sm font-medium text-gray-400 mb-1">标题</label>
                    <input type="text" id="post-title" class="w-full px-4 py-3 bg-dark/50 border border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300" placeholder="请输入博客标题">
                </div>

                <!-- 分类输入框 -->
                <div>
                    <label for="post-category" class="block text-sm font-medium text-gray-400 mb-1">文章分类</label>
                    <input type="text" id="post-category" class="w-full px-4 py-3 bg-dark/50 border border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300" placeholder="请输入分类名称（例如：二次元、技术）">
                    <p class="text-xs text-gray-500 mt-1">分类名称将保存到系统中，便于后续统一管理</p>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-400 mb-1">内容</label>

                    <!-- 富文本编辑器工具栏 -->
                    <div class="rich-text-toolbar rounded-t-lg border border-gray-700 border-b-0">
                        <!-- 字体选择 -->
                        <select id="font-family" class="rich-text-select" title="字体">
                            <option value="Arial, sans-serif">Arial</option>
                            <option value="Georgia, serif">Georgia</option>
                            <option value="Courier New, monospace">Courier New</option>
                            <option value="SimSun, serif">宋体</option>
                            <option value="Microsoft YaHei, sans-serif">微软雅黑</option>
                        </select>

                        <!-- 字号选择 -->
                        <select id="font-size" class="rich-text-select" title="字号">
                            <option value="1">极小</option>
                            <option value="2">小</option>
                            <option value="3" selected>正常</option>
                            <option value="4">中</option>
                            <option value="5">大</option>
                            <option value="6">较大</option>
                            <option value="7">最大</option>
                        </select>

                        <div class="h-6 border-r border-gray-600 mx-1"></div>

                        <!-- 粗体按钮 -->
                        <button type="button" id="bold-btn" class="rich-text-btn" title="粗体">
                            <i class="fa fa-bold"></i>
                            <span class="hidden sm:inline">粗体</span>
                        </button>

                        <!-- 代码块按钮 -->
                        <button type="button" id="code-block-btn" class="rich-text-btn" title="代码块">
                            <i class="fa fa-code"></i>
                            <span class="hidden sm:inline">代码块</span>
                        </button>
                    </div>

                    <!-- 富文本编辑区域 -->
                    <div id="post-content" class="rich-text-editor bg-dark/50 border border-gray-700 rounded-b-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300" contenteditable="true">
                        <p>请输入博客内容...</p>
                    </div>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-400 mb-1">封面图片</label>
                    <div class="flex items-center space-x-4">
                        <div class="relative w-24 h-24 rounded-lg border-2 border-dashed border-gray-600 overflow-hidden">
                            <!-- 默认封面图（在线图片） -->
                            <img id="post-cover-preview" src="https://picsum.photos/id/1015/800/400" alt="封面预览" class="w-full h-full object-cover">
                        </div>
                        <div>
                            <button type="button" id="upload-cover-btn" class="px-4 py-2 bg-primary/20 hover:bg-primary/30 text-primary rounded-lg transition-all duration-300">
                                <i class="fa fa-upload mr-2"></i>上传封面
                            </button>
                            <input type="file" id="post-cover-input" class="hidden" accept="image/*">
                            <p class="text-xs text-gray-500 mt-1">支持 JPG, PNG 格式</p>
                        </div>
                    </div>
                </div>
                <div class="flex justify-end space-x-4">
                    <button type="button" id="cancel-create-post" class="px-6 py-3 bg-gray-800 hover:bg-gray-700 text-white rounded-lg transition-all duration-300">取消</button>
                    <button type="submit" class="px-6 py-3 bg-primary hover:bg-primary/90 text-white rounded-lg transition-all duration-300 transform hover:scale-[1.02]">发布博客</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 模态框：查看博客详情 -->
    <div id="article-detail-modal" class="fixed inset-0 z-50 flex items-center justify-center hidden">
        <div class="absolute inset-0 bg-black/70 backdrop-blur-sm" id="article-detail-overlay"></div>
        <div class="relative bg-dark border border-primary/30 rounded-2xl shadow-2xl p-8 w-full max-w-4xl max-h-[90vh] overflow-y-auto transform transition-all duration-300 scale-95 opacity-0" id="article-detail-modal-content">
            <button id="close-article-detail-modal" class="absolute top-4 right-4 text-gray-400 hover:text-white transition-colors duration-300">
                <i class="fa fa-times text-xl"></i>
            </button>
            <div id="article-detail-content">
                <!-- 博客详情内容将通过JavaScript动态加载 -->
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <script>
    // DOM元素缓存
    const dom = {
        mobileMenuBtn: document.getElementById('mobile-menu-btn'),
        mobileMenu: document.getElementById('mobile-menu'),
        loginBtn: document.getElementById('login-btn'),
        registerBtn: document.getElementById('register-btn'),
        logoutBtn: document.getElementById('logout-btn'),
        createPostBtn: document.getElementById('create-post-btn'),
        mobileCreatePostBtn: document.getElementById('mobile-create-post-btn'),
        userMenu: document.getElementById('user-menu'),
        guestMenu: document.getElementById('guest-menu'),
        usernameEl: document.getElementById('username'),
        userAvatarEl: document.getElementById('user-avatar'),
        loginModal: document.getElementById('login-modal'),
        loginModalContent: document.getElementById('login-modal-content'),
        closeLoginModal: document.getElementById('close-login-modal'),
        loginOverlay: document.getElementById('login-overlay'),
        registerModal: document.getElementById('register-modal'),
        registerModalContent: document.getElementById('register-modal-content'),
        closeRegisterModal: document.getElementById('close-register-modal'),
        registerOverlay: document.getElementById('register-overlay'),
        createPostModal: document.getElementById('create-post-modal'),
        createPostModalContent: document.getElementById('create-post-modal-content'),
        closeCreatePostModal: document.getElementById('close-create-post-modal'),
        createPostOverlay: document.getElementById('create-post-overlay'),
        cancelCreatePost: document.getElementById('cancel-create-post'),
        uploadCoverBtn: document.getElementById('upload-cover-btn'),
        postCoverInput: document.getElementById('post-cover-input'),
        postCoverPreview: document.getElementById('post-cover-preview'),
        switchToRegister: document.getElementById('switch-to-register'),
        switchToLogin: document.getElementById('switch-to-login'),
        articlesContainer: document.getElementById('articles-container'),
        loadMoreBtn: document.getElementById('load-more-btn'),
        articleDetailModal: document.getElementById('article-detail-modal'),
        articleDetailModalContent: document.getElementById('article-detail-modal-content'),
        articleDetailContent: document.getElementById('article-detail-content'),
        closeArticleDetailModal: document.getElementById('close-article-detail-modal'),
        articleDetailOverlay: document.getElementById('article-detail-overlay'),

        // 富文本编辑器元素
        postContent: document.getElementById('post-content'),
        fontFamilySelect: document.getElementById('font-family'),
        fontSizeSelect: document.getElementById('font-size'),
        boldBtn: document.getElementById('bold-btn'),
        codeBlockBtn: document.getElementById('code-block-btn')
    };

    // 分页相关
    let currentPage = 1;
    let isLoading = false;

    // 初始化
    document.addEventListener('DOMContentLoaded', () => {
        checkAuth();
        loadArticles();
        bindEvents();
        initRichTextEditor();
    });

    // 初始化富文本编辑器
    function initRichTextEditor() {
        // 为编辑器设置默认焦点行为
        dom.postContent.addEventListener('focus', () => {
            // 如果是默认文本，清空
            if (dom.postContent.innerHTML.trim() === '<p>请输入博客内容...</p>') {
                dom.postContent.innerHTML = '';
            }
        });

        // 失去焦点时，如果为空则显示提示文本
        dom.postContent.addEventListener('blur', () => {
            if (dom.postContent.innerHTML.trim() === '') {
                dom.postContent.innerHTML = '<p>请输入博客内容...</p>';
            }
        });

        // 检查初始状态
        if (dom.postContent.innerHTML.trim() === '') {
            dom.postContent.innerHTML = '<p>请输入博客内容...</p>';
        }
    }

    // 统一事件绑定
    function bindEvents() {
        // 移动菜单按钮事件
        dom.mobileMenuBtn.addEventListener('click', toggleMobileMenu);

        // 点击页面其他区域关闭移动菜单
        document.addEventListener('click', (e) => {
            const isMenuBtn = dom.mobileMenuBtn.contains(e.target);
            const isMenu = dom.mobileMenu.contains(e.target);
            if (!isMenuBtn && !isMenu && !dom.mobileMenu.classList.contains('hidden')) {
                closeMobileMenu();
            }
        });

        // 登录/注册/登出按钮事件
        dom.loginBtn.addEventListener('click', () => openModal(dom.loginModal, dom.loginModalContent));
        dom.registerBtn.addEventListener('click', () => openModal(dom.registerModal, dom.registerModalContent));
        dom.logoutBtn.addEventListener('click', handleLogout);

        // 创建博客按钮事件
        [dom.createPostBtn, dom.mobileCreatePostBtn].forEach(btn => {
            btn.addEventListener('click', handleCreatePostClick);
        });

        // 关闭模态框事件
        dom.closeLoginModal.addEventListener('click', () => closeModal(dom.loginModal, dom.loginModalContent));
        dom.loginOverlay.addEventListener('click', () => closeModal(dom.loginModal, dom.loginModalContent));
        dom.closeRegisterModal.addEventListener('click', () => closeModal(dom.registerModal, dom.registerModalContent));
        dom.registerOverlay.addEventListener('click', () => closeModal(dom.registerModal, dom.registerModalContent));
        dom.closeCreatePostModal.addEventListener('click', () => closeModal(dom.createPostModal, dom.createPostModalContent));
        dom.createPostOverlay.addEventListener('click', () => closeModal(dom.createPostModal, dom.createPostModalContent));
        dom.cancelCreatePost.addEventListener('click', () => closeModal(dom.createPostModal, dom.createPostModalContent));

        // 封面上传事件
        dom.uploadCoverBtn.addEventListener('click', () => dom.postCoverInput.click());
        dom.postCoverInput.addEventListener('change', handleCoverUpload);

        // 切换登录/注册
        dom.switchToRegister.addEventListener('click', () => switchAuthModal('register'));
        dom.switchToLogin.addEventListener('click', () => switchAuthModal('login'));

        // 加载更多
        dom.loadMoreBtn.addEventListener('click', () => loadArticles(currentPage + 1));

        // 关闭文章详情
        dom.closeArticleDetailModal.addEventListener('click', () => closeModal(dom.articleDetailModal, dom.articleDetailModalContent));
        dom.articleDetailOverlay.addEventListener('click', () => closeModal(dom.articleDetailModal, dom.articleDetailModalContent));


        // 表单提交事件
        document.getElementById('login-form').addEventListener('submit', handleLoginSubmit);
        document.getElementById('register-form').addEventListener('submit', handleRegisterSubmit);
        document.getElementById('create-post-form').addEventListener('submit', handleCreatePostSubmit);

        // 富文本编辑器事件绑定
        dom.fontFamilySelect.addEventListener('change', () => applyFontFamily());
        dom.fontSizeSelect.addEventListener('change', () => applyFontSize());
        dom.boldBtn.addEventListener('click', () => toggleBold());
        dom.codeBlockBtn.addEventListener('click', () => toggleCodeBlock());

        // 监听选择事件，更新按钮状态
        document.addEventListener('selectionchange', updateRichTextButtonsState);
    }

    // 富文本编辑器功能实现
    function applyFontFamily() {
        const fontFamily = dom.fontFamilySelect.value;
        document.execCommand('fontName', false, fontFamily);
        dom.postContent.focus();
    }

    function applyFontSize() {
        const fontSize = dom.fontSizeSelect.value;
        document.execCommand('fontSize', false, fontSize);
        dom.postContent.focus();
    }

    function toggleBold() {
        document.execCommand('bold', false, null);
        dom.postContent.focus();
    }

    function toggleCodeBlock() {
        // 检查是否已选择文本
        const selection = window.getSelection();
        if (selection.rangeCount > 0) {
            const range = selection.getRangeAt(0);

            // 检查选中的内容是否已经在pre标签中
            const parentPre = findParentTag(selection.anchorNode, 'pre');

            if (parentPre) {
                // 如果已经在pre标签中，移除代码块格式
                const codeContent = parentPre.textContent;
                parentPre.parentNode.replaceChild(document.createTextNode(codeContent), parentPre);
            } else {
                // 否则添加代码块格式
                const selectedContent = range.extractContents();
                const pre = document.createElement('pre');
                const code = document.createElement('code');
                code.appendChild(selectedContent);
                pre.appendChild(code);
                range.insertNode(pre);

                // 在代码块后添加一个新段落
                const p = document.createElement('p');
                p.innerHTML = '<br>'; // 添加一个空行
                range.setStartAfter(pre);
                range.setEndAfter(pre);
                range.insertNode(p);

                // 将光标定位到新段落
                range.setStart(p, 0);
                range.setEnd(p, 0);
                selection.removeAllRanges();
                selection.addRange(range);
            }
        } else {
            // 如果没有选择文本，插入一个空的代码块
            const pre = document.createElement('pre');
            pre.innerHTML = '<code><br></code>';

            const selection = window.getSelection();
            if (selection.rangeCount > 0) {
                const range = selection.getRangeAt(0);
                range.deleteContents();
                range.insertNode(pre);

                // 在代码块后添加一个新段落
                const p = document.createElement('p');
                p.innerHTML = '<br>';
                range.setStartAfter(pre);
                range.setEndAfter(pre);
                range.insertNode(p);

                // 将光标定位到代码块内
                range.setStart(pre.querySelector('code'), 0);
                range.setEnd(pre.querySelector('code'), 0);
                selection.removeAllRanges();
                selection.addRange(range);
            }
        }
        dom.postContent.focus();
    }

    // 查找父级标签
    function findParentTag(node, tagName) {
        let currentNode = node;
        while (currentNode && currentNode.nodeType === 1) {
            if (currentNode.tagName.toLowerCase() === tagName.toLowerCase()) {
                return currentNode;
            }
            currentNode = currentNode.parentNode;
        }
        return null;
    }

    // 更新富文本按钮状态
    function updateRichTextButtonsState() {
        // 更新粗体按钮状态
        const isBold = document.queryCommandState('bold');
        dom.boldBtn.classList.toggle('active', isBold);

        // 更新代码块按钮状态
        const selection = window.getSelection();
        let isInCodeBlock = false;

        if (selection.rangeCount > 0) {
            const parentPre = findParentTag(selection.anchorNode, 'pre');
            isInCodeBlock = !!parentPre;
        }

        dom.codeBlockBtn.classList.toggle('active', isInCodeBlock);
    }

    // 移动菜单切换
    function toggleMobileMenu() {
        dom.mobileMenu.classList.toggle('hidden');
        const icon = dom.mobileMenuBtn.querySelector('i');
        if (dom.mobileMenu.classList.contains('hidden')) {
            icon.classList.replace('fa-times', 'fa-bars');
        } else {
            icon.classList.replace('fa-bars', 'fa-times');
        }
    }

    // 关闭移动菜单
    function closeMobileMenu() {
        dom.mobileMenu.classList.add('hidden');
        const icon = dom.mobileMenuBtn.querySelector('i');
        icon.classList.replace('fa-times', 'fa-bars');
    }

    // 处理登出
    function handleLogout() {
        fetch('/api/logout/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCSRFToken()
            }
        })
        .then(response => {
            if (response.status === 200) {
                checkAuth();
                showToast('已成功登出');
            } else {
                throw new Error('登出失败');
            }
        })
        .catch(error => showToast(error.message, true));
    }

    // 处理创建博客点击
    function handleCreatePostClick() {
        fetch('/api/profile/')
            .then(response => {
                if (response.status === 200) {
                    openModal(dom.createPostModal, dom.createPostModalContent);
                    closeMobileMenu();
                } else {
                    throw new Error('请先登录');
                }
            })
            .catch(error => {
                showToast(error.message, true);
                openModal(dom.loginModal, dom.loginModalContent);
                closeMobileMenu();
            });
    }

    // 处理封面上传
    function handleCoverUpload(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (event) => {
                dom.postCoverPreview.src = event.target.result;
            };
            reader.readAsDataURL(file);
        }
    }

    // 切换登录/注册模态框
    function switchAuthModal(type) {
        if (type === 'register') {
            closeModal(dom.loginModal, dom.loginModalContent);
            setTimeout(() => openModal(dom.registerModal, dom.registerModalContent), 300);
        } else {
            closeModal(dom.registerModal, dom.registerModalContent);
            setTimeout(() => openModal(dom.loginModal, dom.loginModalContent), 300);
        }
    }

    // 处理登录提交
    function handleLoginSubmit(e) {
        e.preventDefault();
        const username = document.getElementById('login-username').value;
        const password = document.getElementById('login-password').value;

        fetch('/api/login/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCSRFToken()
            },
            body: JSON.stringify({ username, password })
        })
        .then(response => {
            if (response.status === 200) {
                closeModal(dom.loginModal, dom.loginModalContent);
                checkAuth();
                showToast('登录成功');
            } else {
                return response.json().then(data => {
                    throw new Error(data.message || '登入失败');
                });
            }
        })
        .catch(error => showToast(error.message, true));
    }

    // 处理注册提交
    function handleRegisterSubmit(e) {
        e.preventDefault();
        const username = document.getElementById('register-username').value;
        const email = document.getElementById('register-email').value;
        const password = document.getElementById('register-password').value;
        const confirmPassword = document.getElementById('register-confirm-password').value;

        if (password !== confirmPassword) {
            showToast('两次输入的密码不一致', true);
            return;
        }

        fetch('/api/register/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCSRFToken()
            },
            body: JSON.stringify({ username, email, password })
        })
        .then(response => {
            if (response.status === 201) {
                closeModal(dom.registerModal, dom.registerModalContent);
                checkAuth();
                showToast('注册成功');
            } else {
                return response.json().then(data => {
                    throw new Error(data.message || '注册失败');
                });
            }
        })
        .catch(error => showToast(error.message, true));
    }

    // 处理创建博客提交 - 将分类名称保存到blog_api_category表
    function handleCreatePostSubmit(e) {
        e.preventDefault();
        const title = document.getElementById('post-title').value;
        // 获取富文本内容
        const content = dom.postContent.innerHTML;
        const coverImage = dom.postCoverInput.files[0];
        const categoryName = document.getElementById('post-category').value.trim();

        // 验证富文本内容
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = content;
        const textContent = tempDiv.textContent.trim();

        if (!title || !textContent || textContent === '请输入博客内容...') {
            showToast('标题和内容不能为空', true);
            return;
        }

        // 先检查分类是否存在，如果不存在则创建
        const handleCategory = async () => {
            if (!categoryName) return null;

            try {
                // 检查分类是否已存在
                const checkResponse = await fetch(`/api/categories/check/?name=${encodeURIComponent(categoryName)}`);
                if (checkResponse.ok) {
                    const data = await checkResponse.json();
                    if (data.exists) {
                        return data.id; // 返回已存在的分类ID
                    }
                }

                // 创建新分类
                const createResponse = await fetch('/api/categories/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCSRFToken()
                    },
                    body: JSON.stringify({ name: categoryName })
                });

                if (createResponse.status === 201) {
                    const newCategory = await createResponse.json();
                    return newCategory.id; // 返回新创建的分类ID
                }

                throw new Error('创建分类失败');
            } catch (error) {
                console.error('分类处理失败:', error);
                showToast('分类处理失败，将使用默认分类', true);
                return null;
            }
        };

        // 处理分类并提交文章
        handleCategory().then(categoryId => {
            const formData = new FormData();
            formData.append('title', title);
            formData.append('content', content); // 提交HTML内容
            if (coverImage) formData.append('cover_image', coverImage);
            if (categoryId) formData.append('category_id', categoryId);

            fetch('/api/articles/', {
                method: 'POST',
                headers: { 'X-CSRFToken': getCSRFToken() },
                body: formData
            })
            .then(response => {
                if (response.status === 201) {
                    closeModal(dom.createPostModal, dom.createPostModalContent);
                    showToast(`博客发布成功，分类"${categoryName || '未分类'}"已保存`);
                    // 重置表单并刷新列表
                    document.getElementById('create-post-form').reset();
                    dom.postCoverPreview.src = 'https://picsum.photos/id/1015/800/400';
                    dom.postContent.innerHTML = '<p>请输入博客内容...</p>';
                    dom.articlesContainer.innerHTML = '';
                    currentPage = 1;
                    loadArticles();
                } else {
                    return response.json().then(data => {
                        throw new Error(data.message || '发布失败');
                    });
                }
            })
            .catch(error => showToast(error.message, true));
        });
    }

    // 检查用户认证状态
    function checkAuth() {
        fetch('/api/profile/')
            .then(response => {
                if (response.status === 200) return response.json();
                throw new Error('未登录');
            })
            .then(data => {
                // 已登录状态
                dom.userMenu.classList.remove('hidden');
                dom.userMenu.classList.add('flex');
                dom.guestMenu.classList.add('hidden');
                dom.guestMenu.classList.remove('flex');
                dom.usernameEl.textContent = data.username;
                if (data.avatar) dom.userAvatarEl.src = data.avatar;
            })
            .catch(() => {
                // 未登录状态
                dom.userMenu.classList.add('hidden');
                dom.userMenu.classList.remove('flex');
                dom.guestMenu.classList.remove('hidden');
                dom.guestMenu.classList.add('flex');
            });
    }

    // 加载博客文章
    function loadArticles(page = 1) {
        if (isLoading) return;

        isLoading = true;
        dom.loadMoreBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>加载中...';

        fetch(`/api/articles/?page=${page}`)
            .then(response => {
                if (!response.ok) throw new Error('获取文章失败');
                return response.json();
            })
            .then(data => {
                data.forEach(article => {
                    const articleEl = createArticleCard(article);
                    dom.articlesContainer.appendChild(articleEl);
                });

                currentPage = page;
                isLoading = false;
                dom.loadMoreBtn.innerHTML = '加载更多 <i class="fa fa-refresh ml-2"></i>';

                // 控制加载更多按钮显示
                if (data.length < 10) {
                    dom.loadMoreBtn.style.display = 'none';
                } else {
                    dom.loadMoreBtn.style.display = 'inline-block';
                }
            })
            .catch(error => {
                console.error('加载文章出错:', error);
                showToast('加载文章失败，请重试', true);
                isLoading = false;
                dom.loadMoreBtn.innerHTML = '加载更多 <i class="fa fa-refresh ml-2"></i>';
            });
    }

    // 创建博客卡片 - 展示从blog_api_category表获取的分类名称
    function createArticleCard(article) {
        const card = document.createElement('article');
        const coverImage = article.cover_image || 'https://picsum.photos/id/1015/800/400';

        // 从文章数据中获取分类名称（来自blog_api_category表）
        const categoryName = article.category ? article.category.name : '未分类';
        const categoryClass = article.category ? 'category-tag' : 'category-tag uncategorized';

        // 处理文章摘要，从HTML中提取纯文本
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = article.content;
        const plainText = tempDiv.textContent.substring(0, 150);

        card.className = 'bg-dark/60 backdrop-blur-md rounded-2xl overflow-hidden shadow-lg border border-primary/20 transition-all duration-300 hover:shadow-xl hover:scale-[1.01]';
        card.innerHTML = `
            <div class="md:flex relative">
                <!-- 右上角分类标签 -->
                <span class="${categoryClass}">${categoryName}</span>

                <div class="md:w-1/3">
                    <img src="${coverImage}" alt="${article.title}" class="h-48 md:h-full w-full object-cover">
                </div>
                <div class="p-6 md:w-2/3">
                    <div class="flex items-center space-x-2 mb-3">
                        <img src="${article.author.avatar || 'https://picsum.photos/id/64/200/200'}" alt="${article.author.username}" class="w-8 h-8 rounded-full object-cover">
                        <span class="text-sm text-gray-400">${article.author.username}</span>
                        <span class="text-xs text-gray-500">· ${formatDate(article.created_at)}</span>
                    </div>
                    <h2 class="text-xl font-bold text-white mb-2 hover:text-primary transition-colors duration-300 article-title">${article.title}</h2>
                    <p class="text-gray-400 mb-4 line-clamp-3">${plainText}${article.content.length > 150 ? '...' : ''}</p>
                    <div class="flex items-center justify-between">
                        <div class="flex items-center space-x-4">
                            <button class="like-btn flex items-center text-gray-400 hover:text-primary transition-colors duration-300 ${article.liked_by_user ? 'text-primary' : ''}">
                                <i class="fa fa-heart-o mr-1 ${article.liked_by_user ? 'fa-heart' : ''}"></i>
                                <span>${article.likes_count}</span>
                            </button>
                            <button class="comment-btn flex items-center text-gray-400 hover:text-primary transition-colors duration-300">
                                <i class="fa fa-comment-o mr-1"></i>
                                <span>${article.comments_count}</span>
                            </button>
                        </div>
                        <button class="read-more-btn text-primary hover:underline transition-colors duration-300">阅读更多</button>
                    </div>
                </div>
            </div>
        `;

        // 绑定阅读更多按钮事件
        card.querySelector('.read-more-btn').addEventListener('click', () => fetchArticleDetail(article.id));

        // 绑定点赞按钮事件
        const likeBtn = card.querySelector('.like-btn');
        likeBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            toggleLike(article.id, likeBtn);
        });

        return card;
    }

    // 打开模态框
    function openModal(modal, content) {
        modal.classList.remove('hidden');
        setTimeout(() => {
            content.classList.remove('scale-95', 'opacity-0');
            content.classList.add('scale-100', 'opacity-100');
        }, 10);
    }

    // 关闭模态框
    function closeModal(modal, content) {
        content.classList.remove('scale-100', 'opacity-100');
        content.classList.add('scale-95', 'opacity-0');
        setTimeout(() => modal.classList.add('hidden'), 300);
    }

    // 获取CSRF令牌
    function getCSRFToken() {
        const meta = document.querySelector('meta[name="csrf-token"]');
        return meta ? meta.getAttribute('content') : getCookie('csrftoken');
    }

    // 获取Cookie
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // 格式化日期
    function formatDate(dateString) {
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    // 显示提示消息
    function showToast(message, isError = false) {
        const toast = document.createElement('div');
        toast.className = `fixed bottom-4 right-4 px-6 py-3 rounded-lg shadow-lg transform transition-all duration-500 z-50 translate-y-16 opacity-0 ${
            isError ? 'bg-red-600 text-white' : 'bg-primary text-white'
        }`;
        toast.textContent = message;

        document.body.appendChild(toast);

        // 显示动画
        setTimeout(() => {
            toast.classList.remove('translate-y-16', 'opacity-0');
        }, 10);

        // 自动隐藏
        setTimeout(() => {
            toast.classList.add('translate-y-16', 'opacity-0');
            setTimeout(() => document.body.removeChild(toast), 500);
        }, 3000);
    }

    // 获取文章详情
    function fetchArticleDetail(articleId) {
        fetch(`/api/articles/${articleId}/`)
            .then(response => {
                if (!response.ok) throw new Error('获取文章详情失败');
                return response.json();
            })
            .then(articleDetail => {
                // 并行获取评论
                return Promise.all([
                    articleDetail,
                    fetch(`/api/articles/${articleId}/comments/`).then(res => res.ok ? res.json() : [])
                ]);
            })
            .then(([articleDetail, comments]) => {
                articleDetail.comments = comments;
                renderArticleDetail(articleDetail);
                openModal(dom.articleDetailModal, dom.articleDetailModalContent);
            })
            .catch(error => {
                console.error('加载文章详情出错:', error);
                showToast('加载文章详情失败，请重试', true);
            });
    }

    // 渲染文章详情
    function renderArticleDetail(article) {
        const comments = article.comments || [];
        const coverImage = article.cover_image || 'https://picsum.photos/id/1015/800/400';
        const categoryName = article.category ? article.category.name : '未分类';

        dom.articleDetailContent.innerHTML = `
            <div class="mb-6">
                <!-- 详情页也显示分类标签 -->
                <span class="category-tag ${article.category ? '' : 'uncategorized'}">${categoryName}</span>

                <img src="${coverImage}" alt="${article.title}" class="w-full h-64 md:h-80 object-cover rounded-xl">
                <div class="flex items-center space-x-2 mt-4">
                    <img src="${article.author.avatar || 'https://picsum.photos/id/64/200/200'}" alt="${article.author.username}" class="w-10 h-10 rounded-full object-cover">
                    <div>
                        <h3 class="font-medium text-white">${article.author.username}</h3>
                        <p class="text-xs text-gray-400">发布于 ${formatDate(article.created_at)}</p>
                    </div>
                </div>
                <h1 class="text-2xl md:text-3xl font-bold text-white mt-4">${article.title}</h1>
                <div class="flex items-center space-x-4 mt-4">
                    <button class="like-btn flex items-center text-gray-400 hover:text-primary transition-colors duration-300 ${article.liked_by_user ? 'text-primary' : ''}">
                        <i class="fa fa-heart-o mr-1 ${article.liked_by_user ? 'fa-heart' : ''}"></i>
                        <span>${article.likes_count}</span>
                    </button>
                    <button class="comment-btn flex items-center text-gray-400 hover:text-primary transition-colors duration-300">
                        <i class="fa fa-comment-o mr-1"></i>
                        <span>${comments.length}</span>
                    </button>
                </div>
            </div>

            <!-- 富文本内容显示 -->
            <div class="prose prose-invert max-w-none mb-8 rich-text-editor">
                ${article.content}
            </div>

            <div class="border-t border-gray-800 pt-6">
                <h2 class="text-xl font-bold text-white mb-4">评论 (${comments.length})</h2>

                <div class="space-y-4 mb-8">
                    ${comments.length > 0 ? comments.map(comment => `
                        <div class="flex space-x-4">
                            <img src="${comment.user.avatar || 'https://picsum.photos/id/64/200/200'}" alt="${comment.user.username}" class="w-10 h-10 rounded-full object-cover">
                            <div class="flex-1">
                                <div class="flex items-center justify-between">
                                    <h4 class="font-medium text-white">${comment.user.username}</h4>
                                    <span class="text-xs text-gray-500">${formatDate(comment.created_at)}</span>
                                </div>
                                <p class="text-gray-300 mt-1">${comment.content}</p>
                            </div>
                        </div>
                    `).join('') : '<p class="text-gray-500 italic">暂无评论</p>'}
                </div>

                <div class="border border-gray-700 rounded-xl p-4">
                    <h3 class="text-lg font-medium text-white mb-4">发表评论</h3>
                    <textarea class="w-full px-4 py-3 bg-dark/50 border border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300 resize-none" rows="3" placeholder="分享你的看法..."></textarea>
                    <button id="submit-comment-btn" class="mt-3 px-4 py-2 bg-primary hover:bg-primary/90 text-white rounded-lg transition-all duration-300">提交评论</button>
                </div>
            </div>
        `;

        // 绑定点赞事件
        dom.articleDetailContent.querySelector('.like-btn')
            .addEventListener('click', () => toggleLike(article.id, dom.articleDetailContent.querySelector('.like-btn')));

        // 绑定评论提交事件
        dom.articleDetailContent.querySelector('#submit-comment-btn')
            .addEventListener('click', () => submitComment(article.id));
    }

    // 提交评论
    function submitComment(articleId) {
        const textarea = dom.articleDetailContent.querySelector('textarea');
        const content = textarea.value.trim();
        const submitBtn = dom.articleDetailContent.querySelector('#submit-comment-btn');
        const originalText = submitBtn.innerHTML;

        if (!content) {
            showToast('评论内容不能为空', true);
            return;
        }

        // 显示加载状态
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>提交中...';

        fetch('/api/profile/')
            .then(response => {
                if (!response.ok) throw new Error('请先登录');

                return fetch(`/api/articles/${articleId}/comments/`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCSRFToken()
                    },
                    body: JSON.stringify({ content, article: articleId })
                });
            })
            .then(response => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;

                if (response.ok) return response.json();

                return response.text().then(errorText => {
                    try {
                        const errorData = JSON.parse(errorText);
                        throw new Error(errorData.detail || '提交评论失败');
                    } catch (e) {
                        throw new Error('提交评论失败: ' + errorText);
                    }
                });
            })
            .then(newComment => {
                const container = dom.articleDetailContent.querySelector('.space-y-4');

                // 清空"暂无评论"提示
                if (container.textContent.includes('暂无评论')) container.innerHTML = '';

                // 添加新评论
                container.insertAdjacentHTML('afterbegin', createCommentElement(newComment));

                // 更新评论计数
                dom.articleDetailContent.querySelector('.comment-btn span')
                    .textContent = parseInt(dom.articleDetailContent.querySelector('.comment-btn span').textContent) + 1;

                // 清空输入框
                textarea.value = '';

                // 添加动画
                animateNewComment(container.firstElementChild);
                showToast('评论提交成功');
            })
            .catch(error => {
                showToast(error.message, true);
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;

                if (error.message === '请先登录') {
                    openModal(dom.loginModal, dom.loginModalContent);
                }
            });
    }

    // 创建评论元素
    function createCommentElement(comment) {
        const user = comment.user || { username: '匿名用户' };
        return `
            <div class="flex space-x-4 opacity-0 transition-opacity duration-300" data-comment-id="${comment.id}">
                <img src="${user.avatar || 'https://picsum.photos/id/64/200/200'}" alt="${user.username}" class="w-10 h-10 rounded-full object-cover">
                <div class="flex-1">
                    <div class="flex items-center justify-between">
                        <h4 class="font-medium text-white">${user.username}</h4>
                        <span class="text-xs text-gray-500">刚刚</span>
                    </div>
                    <p class="text-gray-300 mt-1">${comment.content}</p>
                </div>
            </div>
        `;
    }

    // 评论动画
    function animateNewComment(element) {
        setTimeout(() => element.classList.remove('opacity-0'), 50);
    }

    // 点赞/取消点赞
    function toggleLike(articleId, likeBtn) {
        const isLiked = likeBtn.querySelector('i').classList.contains('fa-heart');
        const countEl = likeBtn.querySelector('span');
        const currentCount = parseInt(countEl.textContent);

        fetch('/api/profile/')
            .then(response => {
                if (!response.ok) throw new Error('请先登录');

                return fetch(`/api/articles/${articleId}/like/`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCSRFToken()
                    }
                });
            })
            .then(response => {
                if (response.ok) {
                    // 更新UI
                    if (isLiked) {
                        likeBtn.querySelector('i').classList.replace('fa-heart', 'fa-heart-o');
                        countEl.textContent = currentCount - 1;
                        likeBtn.classList.remove('text-primary');
                        showToast('已取消点赞');
                    } else {
                        likeBtn.querySelector('i').classList.replace('fa-heart-o', 'fa-heart');
                        countEl.textContent = currentCount + 1;
                        likeBtn.classList.add('text-primary');
                        showToast('点赞成功');
                    }
                } else {
                    throw new Error('操作失败');
                }
            })
            .catch(error => {
                showToast(error.message, true);
                if (error.message === '请先登录') {
                    openModal(dom.loginModal, dom.loginModalContent);
                }
            });
    }
    </script>
</body>
</html>
